import React from "react";
import { Image, ScrollView, StyleSheet, Text } from "react-native";
import BasePage from "../BasePage";
import ViewUtils from "../../utils/ViewUtils";
import NavigationBar from "../common/NavigationBar";
import { commonStyles } from "../../configs/commonStyle";
import { inject, observer } from "mobx-react";
import { TouchableOpacity, View } from "react-native-ui-lib";
import ToastUtils from "../../utils/ToastUtils";
import { IconImage } from "../../utils";
import { call, checkCameraPermission, checkRecordAndStorePermission, logger, setClipboardContent } from "../../utils/util";
import NavigateDialog from "../common/NavigateDialog";
import navigator from "../../utils/navigator";
import PermissionDialog from "../common/PermissionDialog";
import Recorder from "../components/Recorder";
import Player from "../components/Player";
import ConfirmDialog from "../common/ConfirmDialog";
import Events from "../../utils/events";
import ExtractedCodeDialog from '../common/dialog/ExtractedCodeDialog';
import { windowWidth } from "../../configs/platform";
import moment from "moment";
import { signOrder } from "../../net/order";

/**
 * 订单详情
 */
@inject("userStore")
@observer
export default class OrderDetails extends BasePage {
  constructor(props) {
    super(props);
    this.recorder = React.createRef();
    this.player = React.createRef();
    this.state = {
      data: {},
      items: [],
    };
  }

  componentDidMount() {
    super.componentDidMount();
    this.loadData();
    this.refreshOrderList = Events.subscribe("RefreshOrderList", () => this.loadData());
  }

  componentWillUnmount() {
    super.componentWillUnmount();
    this.refreshOrderList && this.refreshOrderList.remove();
  }

  loadData = () => {
    const ordNo = this.props.navigation.getParam("ordNo", null);
    let params = {
      token: global.token,
      ordNo,
      showLoading: true,
    };
    axios.get(api.detail, { params })
      .then(res => {
        logger("订单详情", res);
        if (!IsNullOrEmpty(res.result)) {
          this.setState({
            data: res.result.order || {},
            items: res.result.items || [],
          });
        }
      })
      .catch(e => {
        logger("error", e);
        e.msg && ToastUtils.showFailInfo(e.msg);
      });
  };

  /**
   * 签收
   */
  signOrder = (item) => {
    const { location } = this.props.userStore;
    signOrder({
        ordNo: item.ordNo,
        showLoading: true,
        token: global.token,
        longitude: location.longitude,
        latitude: location.latitude,
        altitude: location.altitude || 60,
    }).then(result => {
        ToastUtils.showSuccessInfo("签收成功");
        this.loadData(false);
        Events.publish("RefreshOrderList");
        if (result.code !== 200) {
          uploadError(`调用签收接口失败：${api.signOrder}`,`单号：${item.ordNo}\n, ${JSON.stringify(result)}`)
        }
      }).catch((e) => {
      logger(e);
      e.msg && ToastUtils.showFailInfo(e.msg);
    });
  };

  /**
   * 立即配送
   * @param item
   */
  deliveryOrder = (item) => {
    axios.get(api.deliveryOrder, {
      params: {
        ordNo: item.ordNo,
        showLoading: true,
        token: global.token,
      },
    })
      .then(result => {
        ToastUtils.showSuccessInfo("提交成功");
        this.loadData();
        Events.publish("RefreshOrderList");
      }).catch((e) => {
      logger(e);
      e.msg && ToastUtils.showFailInfo(e.msg);
    });
  };

  navigate = (item) => {
    if (item.addressLng == 0 || item.addressLat == 0) {
      ToastUtils.showFailInfo("配送定位为空，请联系管理员");
      return;
    }
    this.navigateDialog.show({
      latitude: item.addressLat,
      longitude: item.addressLng,
    }, item.address1);
  };

  clickRecord = async (item) => {
    const { recordingNo, playingNo, setValue } = this.props.userStore;
    let isPlaying = item.xmbzNo == playingNo;
    if (isPlaying) {
      // await this.player.current.stop();
      setValue("playingNo", "");
      setValue("showPlayer", "");
      setValue("showPage", "");
    }
    if (!IsNullOrEmpty(recordingNo)) {
      ToastUtils.showInfo("请先停止录音");
      return;
    }
    let permission = await checkRecordAndStorePermission();
    if (permission) {
      setValue("recordingNo", item.xmbzNo);
      setValue("showRecorder", true);
      setValue("showPage", "orderDetail");
      // setTimeout(() => this.recorder.current.startRecord(), 500);
    } else {
      this.permissionDialog.show("录音需要麦克风和存储权限，请开启");
    }
  };

  getRecordText = (data, reRecord) => {
    const { uploadFailList } = this.props.userStore;
    if (uploadFailList.find(item => item.recordingNo == data.xmbzNo)) {
      return (
        <View centerH>
          <Image source={IconImage.icon_uploading} style={styles.btn_icon} />
          <Text style={commonStyles.text_black_12}>上传中</Text>
        </View>
      );
    } else {
      if (reRecord) {
        return (
          <TouchableOpacity activeOpacity={1} centerH throttleTime={1000} onPress={() => {
            this.confirmDialog.show("执行该操作会清除现有录音记录，您确定要重新录音吗?");
          }}>
            <Image source={IconImage.btn_re_record} style={styles.btn_icon} />
            <Text style={commonStyles.text_black_12}>重录</Text>
          </TouchableOpacity>
        );
      }
      return (
        <TouchableOpacity centerH activeOpacity={1} throttleTime={1000}
                          onPress={() => this.clickRecord(data)}>

          <Image source={IconImage.btn_record} style={styles.btn_icon} />
          <Text style={commonStyles.text_black_12}>录音</Text>
        </TouchableOpacity>
      );
    }
  };

  // 提取码处理
  handleCodeConfirm = (result) => {
    const { data } = this.state
    const { orderDetailId, orderId } = result
    if (!orderDetailId || !orderId) {
      ToastUtils.showFailInfo('提取码解析失败，请重试');
      return
    }
    if (data.ordNo != orderId) {
      ToastUtils.showFailInfo("拿错蛋糕了，请仔细检查");
      return;
    }
    const { userInfo } = this.props.userStore;
    const params = {
      token: global.token,
      distributorId: userInfo.distributorId,
      orderDetailId,
      orderId,
      scanTime: moment().format("YYYY-MM-DD HH:mm:ss"),
      showLoading: true,
    }
    return axios.get(api.addDeliveryScanLog, { params })
      .then(res => {
        if (orderId && orderId != res.result.ordNo) {
          ToastUtils.showFailInfo("拿错蛋糕了，请仔细检查");
          return;
        }

        ToastUtils.showSuccessInfo("提取成功");
        this.loadData(false);
      }).catch(e => {
        e.msg && ToastUtils.showFailInfo(e.msg);
        uploadError("提取码调用addDeliveryScanLog失败", `参数：${JSON.stringify(params)},${e.msg}`);
      })
  }

  // 惊喜收集信息
  render_item_question = (data) => {
    return (<View>
      {
        data.questionRelation ?
        <View style={styles.itemWrap}>
          <Text style={commonStyles.text_gray_13}>希望将惊喜送给</Text>
          <Text style={commonStyles.text_black_13}>{data?.questionRelation}</Text>
        </View> : null
      }
      {
        data.questionSex ?
        <View style={styles.itemWrap}>
          <Text style={commonStyles.text_gray_13}>收货人的性别</Text>
          <Text style={commonStyles.text_black_13}>{data?.questionSex}</Text>
        </View> : null
      }
      {
        data.questionAtmosphere ?
        <View style={styles.itemWrap}>
          <Text style={commonStyles.text_gray_13}>期待的气氛</Text>
          <Text style={commonStyles.text_black_13}>{data?.questionAtmosphere}</Text>
        </View> : null
      }
      {
        data.questionPlace ?
        <View style={styles.itemWrap}>
          <Text style={commonStyles.text_gray_13}>小熊猫出现的场景是</Text>
          <Text style={commonStyles.text_black_13}>{data?.questionPlace}</Text>
        </View> : null
      }
    </View>)
  }

  render_item_goods = (items) => {
    return (<View style={{ paddingVertical: 6 }}>
      {
        items && items.map(data => {
          // logger("订单号", data.isScan == 0 ? data.id : "");
          return (
            <View row marginT-5>
              <Image source={data.isScan == 0 ? IconImage.ic_unchecked : IconImage.ic_checked}
                     style={{ width: 17, height: 17, marginRight: 5 }} />
              <View flex>
                <Text style={commonStyles.text_black_13}>
                  {data?.name}（{data?.unit}）（x{data?.num}）
                  {
                    data?.goodsName && data?.goodsName.includes('配送费') ?
                    <Text>（{data?.totalPrice / 100}元）</Text> : null
                  }
                </Text>
                  {
                    data?.tyingRefundContent ? 
                    <Text style={commonStyles.text_red_14}>{`已退商品：${data.tyingRefundContent}`}</Text> : null
                  }
              </View>
            </View>
          );
        })
      }
    </View>)
  }

  render_item_footer = (data, items) => {
    const {
      recordingNo,
      playingNo,
      setValue,
    } = this.props.userStore;
    let isRecording = data.xmbzNo == recordingNo;
    let isPlaying = data.xmbzNo == playingNo;

    const from = this.props.navigation.getParam("from", null);
    let allChecked = true;
    if (!IsNullOrEmpty(items) && items.find(data => data.isScan == 0)) {
      allChecked = false;
    }

    return (<View style={styles.btnWrap}>
      {
        IsNullOrEmpty(from) && (data.ordState == 7 || data.ordState == 8 || data.ordState == 9 || data.ordState == 12) ? null :
        <View flex row>
          <View style={styles.btnItem}>
            <TouchableOpacity
              centerH
              onPress={async () => {
                let permission = await checkCameraPermission();
                if (permission) {
                  navigator.navigate("ScanPage", { from: "orderList", ordNo: data.ordNo });
                } else {
                  this.permissionDialog.show("扫描订单需要获得相机使用权限，请开启");
                }
              }}
              activeOpacity={1} throttleTime={1000}
            >
              <Image source={IconImage.btn_scan} style={styles.btn_icon} />
              <Text style={commonStyles.text_black_12}>扫描</Text>
            </TouchableOpacity>
          </View>
          <View style={styles.btnItem}>
            <TouchableOpacity
              centerH
              onPress={() => {
                this.extractedCodeDialog.show('提取码取件')
              }}
              activeOpacity={1} throttleTime={1000}
            >
              <Image source={IconImage.btn_tiqu} style={styles.btn_icon} />
              <Text style={commonStyles.text_black_12}>提取码</Text>
            </TouchableOpacity>
          </View>
        </View>
      }
      {
        data.ordState == 6 && allChecked == true ?
          <View style={styles.btnItem}>
            <TouchableOpacity centerH onPress={() => this.deliveryOrder(data)} activeOpacity={1}
                              throttleTime={1000}
            >
              <Image source={IconImage.btn_delivery} style={styles.btn_icon} />
              <Text style={commonStyles.text_black_12}>配送</Text>
            </TouchableOpacity>
          </View>
          : null
      }

      {/*<Button label={"中转出发"} style={styles.btn} labelStyle={commonStyles.text_black} />*/}
      {/*<Button label={"中转入库"} style={styles.btn} labelStyle={commonStyles.text_black} />*/}

      {
        (data.addressLng == 0 || data.addressLat == 0) ? null :
          <View style={styles.btnItem}>
            <TouchableOpacity centerH onPress={() => this.navigate(data)} activeOpacity={1} throttleTime={1000}>
              <Image source={IconImage.btn_navigation} style={styles.btn_icon} />
              <Text style={commonStyles.text_black_12}>导航</Text>
            </TouchableOpacity>
          </View>
      }
      {
        data.ordState == 7 ?
          <View style={styles.btnItem}>
            <TouchableOpacity centerH onPress={() => {
              if (data.datediff <= 0) {
                this.signConfirmDialog.show("确定要签收吗？");
              }
            }} activeOpacity={1} throttleTime={1000}
            >
              <Image source={data.datediff > 0 ? IconImage.btn_un_signfor : IconImage.btn_signfor}
                     style={styles.btn_icon} />
              <Text style={data.datediff > 0 ? commonStyles.text_gray_12 : commonStyles.text_black_12}>签收</Text>
            </TouchableOpacity>
          </View>
          : null
      }
      {
        IsNullOrEmpty(data.recordPath) && !isRecording && (data.ordState == 7 || data.ordState == 8) && data.datediff <= 1 ?
          <View style={styles.btnItem}>
            {this.getRecordText(data, false)}
          </View>
          : null
      }
      {
        !IsNullOrEmpty(data.recordPath) && !isRecording && data.datediff <= 1 ?
          <View style={styles.btnItem}>
            {this.getRecordText(data, true)}
          </View>
          : null
      }
      {
        !IsNullOrEmpty(data.recordPath) && !isPlaying ?
          <View style={styles.btnItem}>
            <TouchableOpacity centerH activeOpacity={1} onPress={() => {
              if (isRecording) {
                ToastUtils.showFailInfo("正在录音，不能播放");
                return;
              }
              if (isPlaying == false) {
                setValue("playingNo", data.xmbzNo);
                setValue("showPlayer", data.recordPath);
                setValue("showPage", "orderDetail");
                // setTimeout(() => this.player.current.play(data.recordPath), 500);
              }
            }}>
              <Image source={IconImage.btn_play} style={styles.btn_icon} />
              <Text style={commonStyles.text_black_12}>播放</Text>
            </TouchableOpacity>
          </View>
          : null
      }
    </View>)
  }

  render() {
    const { data, items } = this.state;
    const {
      showRecorder,
      showPlayer,
      showPage,
      uploadFailList,
    } = this.props.userStore;
    logger("更新", uploadFailList);

    const danceLabelMap = {
      0: '不跳舞',
      1: '跳舞',
      2: '-',
    }

    return (
      <View useSafeArea style={commonStyles.body_primary}>
        <NavigationBar
          leftButton={ViewUtils.getLeftButton(() => this._onBackPress())}
          backgroundColor={"transparent"}
          title={"订单操作"} />
        <View style={commonStyles.container}>
          <ScrollView style={commonStyles.scrollStyle}>
            <View>
              <View style={styles.titleWrap}>
                <TouchableOpacity activeOpacity={1} onPress={() => setClipboardContent(data?.xmbzNo)}>
                  <Text style={commonStyles.text_black_14}>单号：{data?.xmbzNo}</Text>
                </TouchableOpacity>
                <Text style={commonStyles.text_black_14}>{data?.delyTime} {data?.delySTime}-{data?.delyETime}</Text>
              </View>
              <View style={styles.contentWrap}>
                <View style={styles.itemWrap}>
                  <Text style={commonStyles.text_gray_13}>状态</Text>
                  <Text style={commonStyles.text_blue_13}>{data?.ordStateName}</Text>
                </View>
                <View style={styles.itemWrap}>
                  <Text style={commonStyles.text_gray_13}>收货人</Text>
                  <Text style={commonStyles.text_black_13}>{data?.cneeName}</Text>
                </View>
                <View style={styles.itemWrap}>
                  <Text style={commonStyles.text_gray_13}>分仓</Text>
                  <Text style={commonStyles.text_black_13}>{data?.invoiceHeader}</Text>
                </View>
                {/* <View style={styles.itemWrap}>
                  <Text style={commonStyles.text_gray_13}>跳舞属性</Text>
                  <Text style={commonStyles.text_black_13}>{data ? danceLabelMap[data.isDance] : '-'}</Text>
                </View> */}
                <View style={styles.itemWrap}>
                  <Text style={commonStyles.text_gray_13}>下单电话</Text>
                  {
                    data.bookTelNo && !data.bookTelNo.includes("*") ?
                      <TouchableOpacity onPress={() => call(data?.bookTelNo,data?.ordNo)}>
                        <Text style={commonStyles.text_black_13}>{data?.bookTelNo}</Text>
                      </TouchableOpacity>
                      : <Text style={commonStyles.text_black_13}>{data?.bookTelNo}</Text>
                  }
                </View>
                <View style={styles.itemWrap}>
                  <Text style={commonStyles.text_gray_13}>联系电话</Text>
                  {
                    data.cneeTel && !data.cneeTel.includes("*") ?
                      <TouchableOpacity onPress={() => call(data?.cneeTel,data?.ordNo)}>
                        <Text style={commonStyles.text_black_13}>{data?.cneeTel}</Text>
                      </TouchableOpacity>
                      : <Text style={commonStyles.text_black_13}>{data?.cneeTel}</Text>
                  }
                </View>
                <View style={styles.itemWrap}>
                  <Text style={commonStyles.text_gray_13}>地址</Text>
                  <View marginL-10 flex right>
                    <Text style={commonStyles.text_black_13}>{data?.address1}</Text>
                  </View>
                </View>
                <View style={styles.itemWrap}>
                  <Text style={commonStyles.text_gray_13}>备注</Text>
                  <Text style={commonStyles.text_black_13}>{data?.delyNeeds}</Text>
                </View>
                {
                  items && items.some(item => item.tyingRefundContent) ? 
                  (<View style={styles.itemWrap}>
                    <Text style={commonStyles.text_gray_13}>搭售退单说明</Text>
                    <Text style={commonStyles.text_red_13}>下拉查看退货详情</Text>
                  </View>) : null
                }
                <View style={styles.itemWrap}>
                  <Text style={commonStyles.text_gray_13}>渠道</Text>
                  <Text style={commonStyles.text_black_13}>{data?.chanName}</Text>
                </View>
                <View style={styles.itemWrap}>
                  <Text style={commonStyles.text_gray_13}>扫码关注</Text>
                  <Text style={commonStyles.text_black_13}>
                    {data.tag == "1" ? "需要" : "不需要"}
                  </Text>
                </View>
                { this.render_item_question(data) }
                { this.render_item_goods(items) }
              </View>
            </View>
            <View style={styles.line} />
            <ScrollView horizontal showsHorizontalScrollIndicator={false} style={{width:windowWidth-30,alignSelf:'center',backgroundColor:'white'}} >
            { this.render_item_footer(data, items) }
            </ScrollView>
          </ScrollView>
        </View>
        <NavigateDialog ref={r => this.navigateDialog = r} />
        <PermissionDialog ref={r => this.permissionDialog = r} />
        <ConfirmDialog ref={r => this.confirmDialog = r} callBack={() => this.clickRecord(data)} />
        <ConfirmDialog ref={r => this.signConfirmDialog = r} callBack={() => this.signOrder(data)} />
        {
          showRecorder && showPage == "orderDetail" ?
            <Recorder onRef={this.recorder} showRecorder={showRecorder} /> : null
        }
        {
          showPlayer && showPage == "orderDetail" ? <Player onRef={this.player} showPlayer={showPlayer} /> : null
        }
        <ExtractedCodeDialog 
          ref={r => (this.extractedCodeDialog = r)}
          callBack={this.handleCodeConfirm}
        />
      </View>
    );
  }
}

const styles = StyleSheet.create({
  btn: { borderRadius: 4, width: 100 },
  button: {
    paddingHorizontal: 10,
    height: 30,
    borderRadius: 4,
    backgroundColor: "#F9D63B",
    ...commonStyles.center,
  },
  btnWrap: {
    flexDirection: "row",
    marginHorizontal: 15,
    // paddingHorizontal:15,
    alignItems: "center",
    flexWrap: "wrap",
    backgroundColor: "white",
    paddingVertical: 5,
  },
  line: {
    height: 1,
    backgroundColor: "#EFEFEF",
    marginHorizontal: 15,
  },
  titleWrap: {
    justifyContent: "space-between",
    flexDirection: "row",
    alignItems: "center",
    borderTopLeftRadius: 4,
    borderTopRightRadius: 4,
    backgroundColor: "#F9D63B",
    marginHorizontal: 15,
    paddingHorizontal: 15,
    paddingVertical: 10,
    marginTop: 15,
  },

  contentWrap: {
    borderBottomLeftRadius: 4,
    borderBottomRightRadius: 4,
    backgroundColor: "white",
    marginHorizontal: 15,
    paddingHorizontal: 15,
    paddingVertical: 10,
  },
  itemWrap: {
    justifyContent: "space-between",
    flexDirection: "row",
    alignItems: "center",
    paddingVertical: 6,
    width: '98%',
    flexWrap: 'wrap',
  },
  buttonsWrap: {
    flexDirection: "row",
    marginHorizontal: 15,
    marginTop: 15,
    alignItems: "center",
  },
  btnItem: { ...commonStyles.center,marginLeft:15, },
  btn_icon: { width: 43, height: 43, marginBottom: 3 },
});
